# -*- coding: utf-8 -*-
# __author__ :Li
# 2022/5/5 16:45
'''
聚水潭API对接
'''
import time
import hashlib
import requests
from urllib.parse import urlencode
import json

class JuShuiTan(object):
    def __init__(self,app_key,app_secret,access_token=''):
        self.app_key = app_key
        self.app_secret = app_secret
        self.access_token = access_token
        self.root_url = 'https://openapi.jushuitan.com'

    def get_header(self,kwargs=None):
        header = {
            'Content-Type':'application/x-www-form-urlencoded;charset=UTF-8'
        }
        if kwargs and type(kwargs) == dict:
            header.update(**kwargs)
        return header

    def get_sign(self, data):
        list_data = list(data.keys())
        string_sign = self.app_secret
        sort_list = sorted(list_data)
        for item in sort_list:
            if item == 'sign':
                continue
            string_sign += str(item)
            string_sign += str(data[item])
        sign = hashlib.md5(string_sign.encode('utf-8')).hexdigest()
        return sign

    #通过code获取access_token和refresh_token
    def get_access_token(self,code):
        data = {
            'app_key':self.app_key,
            'timestamp':str(int(time.time())),
            'grant_type':'authorization_code',
            'charset':'utf-8',
            'code':code,
        }
        path = '/openWeb/auth/accessToken'
        sign = self.get_sign(data)
        data['sign'] = sign
        params = urlencode(data)
        path += '?%s'%params
        response = requests.post(url=self.root_url + path,data=json.dumps(data,ensure_ascii=False),headers=self.get_header())
        return json.loads(response.text)


    #更新授权令牌
    def refresh_token(self,refresh_token):
        '''
        开放平台对访问令牌的过期时间默认设置为30天
        :return:
        '''
        data = {
            'app_key':self.app_key,
            'timestamp':str(int(time.time())),
            'grant_type':'refresh_token',
            'charset':'utf-8',
            'refresh_token':refresh_token,
            'scope':'all'
        }
        path = '/openWeb/auth/refreshToken'
        sign = self.get_sign(data)
        data['sign'] = sign
        url = path + '?' + urlencode(data)
        response = requests.post(url=self.root_url + url,headers=self.get_header())
        if response.status_code == 200:
            return json.loads(response.text)
        print('更新授权令牌失败:%s'%response.text)
        return

    #获取业务授权URL
    def get_auth_url(self,state=''):
        data = {
            'app_key':self.app_key,
            'timestamp':str(int(time.time())),
            'charset':'utf-8',
        }
        sign = self.get_sign(data)
        data['sign'] = sign
        if state:
            data['state'] = state
        auth_url = 'https://openweb.jushuitan.com/auth'
        params = urlencode(data)
        return '%s?%s'%(auth_url,params)

    def request(self,path,data,method='POST',header=None):
        url = self.root_url + path
        params = {
            'app_key':self.app_key,
            'access_token':self.access_token,
            'timestamp':str(int(time.time())),
            'version':'2',
            'charset':'utf-8',
            'biz':json.dumps(data,ensure_ascii=False)
        }
        sign = self.get_sign(params)
        header = self.get_header(header)
        params['sign'] = sign
        if method == 'POST':
            res = requests.post(url,data=urlencode(params),headers=header)
        else:
            url = url + '?' + urlencode(params)
            res = requests.get(url,headers=header)
        return json.loads(res.text)

    from .Order import orders_query
    from .Shop import shops_query
    from .Refund import refund_query

